<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ include file="/wesite/view/common/base.jsp" %>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>选择采购商品</title>
    <%@ include file="/wesite/view/common/common.jsp" %>
</head>
<body>
<div class="aui-searchbar" id="search">
    <div class="aui-searchbar-input">
        <input type="search" placeholder="请输入商品名称或首字母" id="search-input">
        <div class="aui-searchbar-clear-btn">
        </div>
    </div>
    <div class="aui-searchbar-btn" tapmode>搜索</div>
</div>
<div class="shopping-cart">
    <div class="cl"></div>
    <ul class="list">
    </ul>

    <div class="h98"></div>
    <div class="add-product-bottom">
        <div class="fl">
               <span>
                    <input type="checkbox" name="" value="" id="allckb"/>
                    <i>全选</i>
                </span>
        </div>
        <div class="btn fr">
            <span onclick="addSelected();">添加</span>
        </div>
    </div>
</div>
</body>
<script src="${ctx }/plugins/artTemplate/dist/template.js"></script>
<script type="text/javascript" src="${webctx}/script/aui-scroll.js"></script>
<script type="text/javascript">
    var hotsLoading = false;
    var IPageNo = 1;
    var curcount = 0;
    apiready = function () {
        api.parseTapmode();
    }

    /*全选*/
    $("#allckb").click(function () {
        if (this.checked) {
            $(".selectbox input:checkbox").attr("checked", true);
        } else {
            $(".selectbox input:checkbox").attr("checked", false);
        }
    });

    var searchBar = document.querySelector(".aui-searchbar");
    var searchBarInput = document.querySelector(".aui-searchbar input");
    var searchBarBtn = document.querySelector(".aui-searchbar .aui-searchbar-btn");
    var searchBarClearBtn = document.querySelector(".aui-searchbar .aui-searchbar-clear-btn");
    if (searchBar) {
        searchBarInput.onclick = function () {
            searchBarBtn.style.marginRight = 0;
        }
        searchBarInput.oninput = function () {
            searchBarClearBtn.style.display = 'block';
            searchBarBtn.classList.add("aui-text-info");
        }
    }
    searchBarClearBtn.onclick = function () {
        this.style.display = 'none';
        searchBarInput.value = '';
        searchBarBtn.classList.remove("aui-text-info");
    }
    searchBarBtn.onclick = function () {
        $(".aui-searchbar-input").addClass("searchbar-blue-bg");
        searchBarInput.blur();
        $(".list").empty();
        $("#allckb").attr("checked", false);
        IPageNo = 1;
        curcount = 0;
        loadProducts();
    }

    $("#search-input").blur(function () {
        $(".aui-searchbar-input").removeClass("searchbar-blue-bg");
    });

    //减少商品数量
    $('.list').on('click', '.sy_minus', function () {
        var txt = $(this).next();
        var n = parseInt(txt.val());
        n--;
        txt.val(n);
        inputAmount(txt);
    });

    //输入数量
    $('.list').on('change', '.num', function () {
        $(this).val($(this).val().replace(/[^0-9]/g, ''));
        if ($(this).val() == '0' || $(this).val() == '') $(this).val('1');
        if ($(this).attr("maxnum") && $(this).val()) {
            var max = parseInt($(this).attr("maxnum"));
            if (parseInt($(this).val()) > max) $(this).val(max);
        }
    });

    $('.list').on('focus', '.num', function () {
        $(this).select();
    });
    //增加商品数量
    $('.list').on('click', '.sy_plus', function () {
        var txt = $(this).prev();
        var n = parseInt(txt.val());
        n++;
        txt.val(n);
        inputAmount(txt);
    });

    //全选反选
    $('.list').on('click', '.selectbox', function () {
        if ($(this).find("input").is(":checked")) {
            if ($(".list").find(":checked").length == curcount) {
                $("#allckb").attr("checked", true);
            }
        } else {
            $("#allckb").attr("checked", false);
        }
    });

    //加入采购模版
    function addSelected() {
        if (hotsLoading) {
            return false;
        } else {
            hotsLoading = true;
        }
        var seldatas = [];
        $(".list").find(":checked").map(function () {
            seldatas.push({"priceid": $(this).val(), "num": $(this).parents("li").find(".num").val()});
        });
        if (seldatas.length > 0) {
            $w.httpRequest({
                url: "${ctx}/purchasetemp/addproduct",
                data: {"panid":${id}, "data": JSON.stringify(seldatas)},
                ok: function () {
                    window.location.href = "${ctx}/we/purchaseTemplate/${id}";
                },
                fail: function (ret) {
                    new auiToast().fail({
                        title: "加入采购模版失败",
                        duration: 800
                    });
                },
                all: function () {
                    hotsLoading = false;
                }
            })
        } else {
            hotsLoading = false;
            new auiToast().fail({
                title: "请选择商品",
                duration: 800
            });
        }
    }

    var totalPage = 1;
    function loadProducts() {
        if (hotsLoading) {
            return false;
        } else {
            hotsLoading = true;
        }

        $w.httpRequest({
            url: apiroot + "/we/product/WeLoadproducts",
            method: "get",
            data: {
                querylike: $("#search-input").val(),
                pno: IPageNo
            },
            ok: function (ret) {
                hotsLoading = false;
                var data = ret.Data;
                var count = data.resultcount;
                if (count == 0) {
                    $(".empty-page").css("display", "block");
                    $(".shopping-cart").hide();
                    $(".btn-size").hide();
                }
                totalPage = data.pagecount;
                productdata = data.products;
                curcount += productdata.length;
                if (productdata.length > 0) {
                    for (var i = 0; i < productdata.length; i++) {
                        if (productdata[i].B_chanjia && productdata[i].B_chanjia.length > 11) {
                            productdata[i].B_chanjia = productdata[i].B_chanjia.substr(0, 11) + "...";
                        }
                    }
                    IPageNo++;
                    $("#allckb").attr("checked", false);
                    $(".shopping-cart").css("display", "block");
                    $(".btn-size").css("display", "block");
                    showProducts();
                } else {
                    IPageNo = 0;
                }
            }
        })
    }

    function replaceHtmlFileserver(html){

        if(html){

            var sourceHtml = html;
            var fsIndex = -1;
            var targetHtml = "";
            do{
                fsIndex = sourceHtml.indexOf(fileserver);
                if( fsIndex >= 0 ){
                    if( fsIndex != 0 ){
                        targetHtml += sourceHtml.substr( 0 , fsIndex );
                    }
                    targetHtml += getRandomFileserver();
                    if( ( fsIndex + fileserver.length ) < ( sourceHtml.length - 1 ) ){
                        sourceHtml = sourceHtml.substring( fsIndex + fileserver.length );
                    }
                } else {
                    targetHtml += sourceHtml;
                }
            } while ( fsIndex >= 0 );

            return targetHtml;

        }
        return html;
    }

    function showProducts() {
        var h = template('productHtml_list', {
            ctx: ctx,
            fileserver: getRandomFileserver(),
            isuserauth: isuserauth,
            islogin: islogin,
            list: productdata
        });
        var newHtml = replaceHtmlFileserver(h);
        $(".list").append(newHtml);
    }

    $(function () {
        loadProducts();
        var bottomHeight = $("div.h98").height() * 2;
        var scroll = new auiScroll({
            listen: true, //是否监听滚动高度，开启后将实时返回滚动高度
            distance: bottomHeight //判断到达底部的距离，isToBottom为true
        }, function (ret) {
            if (ret.isToBottom) {
                if (IPageNo > 0 && IPageNo <= totalPage) {
                    var toast = new auiToast({});
                    toast.loading({
                        title: "加载中",
                        duration: 300
                    }, function () {
                        setTimeout(function () {
                            toast.hide();
                        }, 300)
                    });

                    loadProducts();
                }
            }
        });
    });

</script>
<script type="text/html" id="productHtml_list">
    {{each list as value i}}
    <li>
        <div class="selectbox"><input type="checkbox" name="productid" value="{{value.id}}"></div>
        <div class="img">
            <a href="{{ctx}}/we/product/{{value.id}}">
                {{if islogin && isuserauth && value.amount <= 0}}
                <div class="not-available-tips">无货</div>
                {{/if}}
                {{if islogin && isuserauth && value.amount > 0 && !value.canbuy}}
                <div class="not-available-tips"></div>
                {{/if}}
                <img src="{{fileserver}}{{value.photo}}" onerror="this.src='{{ctx}}/wesite/images/noimg.jpg'">
            </a>
        </div>
        <div class="con">
            <h3>{{value.productname}} {{value.name}}</h3>
            <div class="data">
                <p>生产厂家：{{value.b_chanjia}}</p>
                <p>规格：{{value.b_guige}}</p>
                <span class="price">
                    {{if !islogin}}
                        <i>登录可见</i>
                    {{else if !isuserauth}}
                        <i>审核通过可见</i>
                    {{else if !value.canbuy && value.amount > 0}}
                        <i>该商品不在销售区域内</i>
                    {{else if islogin && isuserauth}}
                        <i>¥{{value.price}}</i>
                    {{/if}}
                </span>
                <div class="count-box">
                    <i class="sy_minus">-</i>
                    <input class="num focus-auto-select" name="amount" type="number" maxnum="{{value.amount}}"
                           {{if value.amount> 0}}value="1" {{else}} value="0"{{/if}}>
                    <i class="sy_plus">+</i>
                </div>
            </div>
            <div class="cl"></div>
        </div>
    </li>
    {{/each}}
</script>
</html>